package com.yunhui.wx.robot.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yunhui.wx.robot.common.BaseCommon;
import com.yunhui.wx.robot.common.ResCode;

public class TLRobotUtil {

	private static Logger log = LoggerFactory.getLogger(TLRobotUtil.class);
	
	/**
     * 获取可以传输的正确的json格式的请求字符串
     * @param reqMes 输入内容
     * @return
     */
    public static String getReqMes(String reqMes,String userId){
        // 请求json，里面包含reqType，perception，userInfo
        JSONObject reqJson = new JSONObject();
        // 输入类型:0-文本(默认)、1-图片、2-音频       暂只支持文本
        int reqType = 0;
        reqJson.put("reqType",reqType);

        // 输入信息,里面包含inputText，inputImage，selfInfo
        JSONObject perception = new JSONObject();
        // 输入的文本信息
        JSONObject inputText = new JSONObject();
        inputText.put("text",reqMes);
        perception.put("inputText",inputText);
        // 用户信息
        JSONObject userInfo = new JSONObject();
        userInfo.put("apiKey",BaseCommon.TL_ROBOT_API_KEY);
        userInfo.put("userId",userId);

        reqJson.put("perception",perception);
        reqJson.put("userInfo",userInfo);
        return reqJson.toString();
    }
    
    
    
    public static String sendMessgae(String url,String msg){
    	StringBuffer buffer=new StringBuffer();
    	PrintWriter out=null;
    	BufferedReader in=null;
    	String status="";
    	try {
			URL realURL=new URL(url);
			URLConnection connection = realURL.openConnection();
			HttpURLConnection huc=(HttpURLConnection)connection;
			huc.setRequestProperty("Content-Type", "application/json");
			huc.setRequestProperty("x-adviewrtb-version", "2.1");
			huc.setDoOutput(true);
			huc.setDoInput(true);
			out = new PrintWriter(huc.getOutputStream());
			out.write(msg);
			out.flush();
			huc.connect();
			in=new BufferedReader(new InputStreamReader(huc.getInputStream()));
			String line;
			if((line=in.readLine())!=null){
				buffer.append(line);
			}
			status=String.valueOf(huc.getResponseCode());
			log.info("Http返回状态码:[{}]",status);
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			if(out!=null){
				out.close();
			}
			if(in!=null){
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
    	return buffer.toString();
    }
    
    public static String getResultMes(String res){
    	 
        if(StringUtils.isNotBlank(res)){
        	try {
        		JSONObject object = JSON.parseObject(res);
            	JSONObject intent = object.getJSONObject("intent");
            	//获取返回状态码信息
            	Integer code = intent.getInteger("code");
            	log.info("图灵API返回状态码:[{}]",code);
            	String errorMsg = ResCode.findResMsgByCode(code);
            	if(errorMsg==null){
            		 JSONObject result = object.getJSONArray("results").getJSONObject(0);
            		JSONObject values = result.getJSONObject("values");
            		return values.getString("text");
            	}else{
            		log.error(errorMsg);
            	}
			} catch (Exception e) {
				e.printStackTrace();
			}
        }
    	return null;
        
    }
}
